from json import JSONDecodeError

from locust import task, FastHttpUser, constant, run_single_user


class UploadFile(FastHttpUser):
    wait_time = constant(1)
    host = "https://www.retone-hearing.fit"
    # header = {"Content-Type": "application/json"}
    header = {"Cookie": "hearingaid_user=NmE1YWQyZmMtZGMzZC00OGU2LWI5NTgtN2IxMzNjZjRjMDQw",
              "Content-Type": "application/json"}
    with open(r"C:\Users\Administrator\Pictures\R-C.jpg", mode='rb') as image:
        image_rb = image.read()
    files = {'file': image_rb}

    @task
    def upload_file(self):
        url = '/microServiceUser/needAppUserAuth/responseEncode/uploadUserProfile'
        with self.rest('post', url, files=self.files, headers=self.header) as resp:
            try:
                if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()["description"] is not None):
                    resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                else:
                    resp.success()
            except JSONDecodeError:
                resp.failure("Response could not be decoded as JSON")
            except KeyError:
                resp.failure("Response did not contain expected key 'greeting'")


if __name__ == '__main__':
    run_single_user(UploadFile)
